<template>
  <div class="content-wrap info-source" v-loading="loading">
    <div class="content-form tag-scrollbar">
      <template v-if="editable">
        <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="0">
          <el-row :gutter="20">
            <template v-if="(tagInfo.tagKind === 5 && editForm.plfmId) || tagInfo.tagKind !== 5">
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-purpose">数据源</div>
                  <div class="source-content">
                    <el-form-item prop="plfmId">
                      <el-select
                        v-model="editForm.plfmId"
                        :disabled="!editable || tagInfo.tagKind === 5"
                        filterable
                        clearable
                      >
                        <el-option label="---" value=""></el-option>
                        <el-option
                          v-for="item in platforms"
                          :key="item.plfmId"
                          :label="item.plfmNm"
                          :value="item.plfmId"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-purpose">数据库</div>
                  <div class="source-content">
                    <el-form-item prop="dbNm">
                      <el-select
                        v-model="editForm.dbNm"
                        :disabled="!editable || tagInfo.tagKind === 5"
                        filterable
                        clearable
                      >
                        <el-option label="---" value=""></el-option>
                        <el-option
                          v-for="item in dbList"
                          :key="item.dbId"
                          :label="item.dbName"
                          :value="item.dbName"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-blue">数据表</div>
                  <div class="source-content">
                    <el-form-item prop="tableNm">
                      <el-select
                        v-model="editForm.tableNm"
                        :disabled="!editable || tagInfo.tagKind === 5"
                        filterable
                        clearable
                      >
                        <el-option label="---" value=""></el-option>
                        <el-option
                          v-for="item in tableList"
                          :key="item.tableId"
                          :label="item.tableNm"
                          :value="item.tableNm"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
            </template>
            <el-col :span="12">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-blue">{{ tagInfo.tagKind === 4 ? '事件ID' : '字段' }}</div>
                <div class="source-content">
                  <el-form-item prop="fieldNm">
                    <el-input
                      placeholder="请输入字段"
                      v-model="editForm.fieldNm"
                      :disabled="!editable || tagInfo.tagKind === 5"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="source-item">
                <div class="source-title linear-cyan">关联字段</div>
                <div class="source-content rela-content">
                  <el-form-item prop="relaFields">
                    {{ editForm.relaFields.join(',') }}
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12" v-if="tagInfo.tagKind !== 4">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-cyan">取值类型</div>
                <div class="source-content">
                  <el-form-item prop="valueTypeId">
                    <el-select v-model="editForm.valueTypeId" :disabled="!editable">
                      <el-option label="---" value=""></el-option>
                      <el-option
                        v-for="item in $dictList('value_type')"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-red">更新频率</div>
                <div class="source-content">
                  <el-form-item prop="updateFreqId">
                    <!-- <el-radio-group v-model="editForm.updateFreqId" :disabled="!editable">
                      <el-radio v-for="item in $dictList('update_freq')" :key="item.key" :label="item.key">
                        {{ item.value }}
                      </el-radio>
                    </el-radio-group> -->
                    <el-select v-model="editForm.updateFreqId" :disabled="!editable" @change="clearUpdateValue">
                      <el-option
                        v-for="dict in $dictList('update_freq')"
                        :key="dict.key"
                        :value="dict.key"
                        :label="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="source-item">
                <div class="source-title linear-red">
                  更新规则
                  <freq-tips></freq-tips>
                </div>
                <div class="source-content">
                  <el-form-item
                    prop="updateFreqValue"
                    :rules="editForm.updateFreqId === 1 ? { validator: numberRules, trigger: 'blur' } : {}"
                  >
                    <el-date-picker
                      v-model="editForm.updateFreqValue"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择日期"
                      :picker-options="editForm.updateFreqId === 0 ? pickOptions : MonthPickOptions"
                      v-if="editForm.updateFreqId === 0 || editForm.updateFreqId === 4"
                    ></el-date-picker>
                    <el-input
                      v-model="editForm.updateFreqValue"
                      placeholder="请输入更新规则"
                      v-else-if="editForm.updateFreqId === 1"
                    ></el-input>
                    <el-select v-model="editForm.updateFreqValue" v-else>
                      <el-option label="---" value=""></el-option>
                      <template v-if="editForm.updateFreqId === 2">
                        <el-option v-for="item in 7" :key="item" :label="item" :value="item.toString()"></el-option>
                      </template>
                      <template v-else-if="editForm.updateFreqId === 3">
                        <el-option label="月末" value="0"></el-option>
                        <el-option v-for="item in 28" :key="item" :label="item" :value="item.toString()"></el-option>
                      </template>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12" v-if="tagInfo.tagKind === 5">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-purpose">标签数据</div>
                <div class="source-content">
                  <el-button type="primary" size="medium" @click="$refs.registerManualDrawer.showDrawer(tagId)">
                    更新标签数据
                  </el-button>
                  <span class="manual-tips" v-if="editForm.plfmId">
                    <icon-svg name="iconComplete"></icon-svg>
                    导入成功
                  </span>
                  <!-- <span class="deleteBtn" v-if="editForm.plfmId">
                    <el-tooltip effect="dark" content="删除旧数据" placement="top">
                      <el-button
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        circle
                        @click="removeTable"
                      ></el-button>
                    </el-tooltip>
                  </span> -->
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="editForm.syncRecords.length">
            <el-col :span="24">
              <div class="source-item sync-item">
                <div class="source-title linear-blue"><span>数据同步</span></div>
                <div class="source-content">
                  <el-row class="sync-row-title">
                    <el-col :span="6">同步平台</el-col>
                    <el-col :span="6">同步数据库</el-col>
                    <el-col :span="6">同步数据表</el-col>
                    <el-col :span="6">同步字段</el-col>
                  </el-row>
                  <el-row v-for="(item, index) in editForm.syncRecords" :key="item.plfmId">
                    <el-col :span="6">
                      <el-form-item :prop="`syncRecords[${index}].checked`">
                        <el-checkbox v-model="item.checked" @change="changeSync($event, index)">{{
                          item.syncPlfmNm
                        }}</el-checkbox>
                      </el-form-item>
                    </el-col>
                    <!-- <el-col :span="5">{{ item.syncPlfmNm }}</el-col> -->
                    <el-col :span="6">
                      <el-form-item
                        :prop="`syncRecords[${index}].syncDbNm`"
                        :rules="{
                          validator: checkSyncForm,
                          trigger: 'blur'
                        }"
                      >
                        <el-input v-model="item.syncDbNm" :disabled="!item.checked"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        :prop="`syncRecords[${index}].syncTableNm`"
                        :rules="{
                          validator: checkSyncForm,
                          trigger: 'blur'
                        }"
                      >
                        <el-input v-model="item.syncTableNm" :disabled="!item.checked"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        :prop="`syncRecords[${index}].syncFieldNm`"
                        :rules="{
                          validator: checkSyncForm,
                          trigger: 'blur'
                        }"
                      >
                        <el-input v-model="item.syncFieldNm" :disabled="!item.checked"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>
          <div class="params-selection">
            <div class="star"></div>
            <el-form-item label="是否枚举：" label-width="110px" prop="enumTag">
              <el-radio-group v-model="editForm.enumTag" :disabled="!editable">
                <el-radio :label="1">
                  是
                </el-radio>
                <el-radio :label="0">
                  否
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <template v-if="editForm.enumTag === 1">
            <div class="params">
              <el-form-item label="添加方式：" label-width="120px" prop="isEnumImport">
                <el-radio-group v-model="editForm.isEnumImport" :disabled="!editable || editForm.enumVals.length >= 30">
                  <el-radio :label="false">
                    立即填写
                  </el-radio>
                  <el-radio :label="true">
                    批量导入
                  </el-radio>
                </el-radio-group>
                <span class="tips">
                  如枚举值过多，建议使用<span class="tag-click-item" @click="$blank('enums')">批量导入方式</span>添加
                </span>
              </el-form-item>
              <template v-if="!editForm.isEnumImport">
                <el-row :gutter="20" class="params-title">
                  <el-col :span="10">枚举值</el-col>
                  <el-col :span="10">描述</el-col>
                </el-row>
                <el-row :gutter="20" v-for="(item, index) in editForm.enumVals" :key="'enumVals' + index">
                  <el-col :span="10">
                    <el-form-item
                      :prop="'enumVals.' + index + '.cdVal'"
                      :rules="[
                        {
                          required: true,
                          message: '枚举值不能为空',
                          trigger: 'blur'
                        },
                        { max: 100, message: '枚举值不能超过100个字符', trigger: 'blur' }
                      ]"
                    >
                      <el-input
                        v-model="item.cdVal"
                        :placeholder="'枚举值' + (index + 1)"
                        :disabled="!editable"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item
                      :prop="'enumVals.' + index + '.cdDesc'"
                      label-width="0"
                      :rules="{ max: 500, message: '描述不能超过500个字符', trigger: 'blur' }"
                    >
                      <el-input v-model="item.cdDesc" placeholder="描述" :disabled="!editable"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4" v-if="editable">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      size="mini"
                      circle
                      @click="addParams('enumVals')"
                    ></el-button>
                    <el-button
                      type="warning"
                      icon="el-icon-minus"
                      size="mini"
                      circle
                      @click="remove('enumVals', index)"
                      v-if="index !== 0"
                    ></el-button>
                  </el-col>
                </el-row>
              </template>
            </div>
          </template>
          <div class="params-selection">
            <div class="star"></div>
            <el-form-item label="是否带参数：" label-width="110px" prop="haveParam">
              <el-radio-group v-model="editForm.haveParam" :disabled="!editable">
                <el-radio :label="1">
                  是
                </el-radio>
                <el-radio :label="0">
                  否
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <template v-if="editForm.haveParam === 1">
            <div class="params">
              <el-row :gutter="20" class="params-title">
                <el-col :span="5">参数名称</el-col>
                <el-col :span="4">参数类型</el-col>
                <el-col :span="2">是否枚举</el-col>
                <el-col :span="4">参数字段</el-col>
                <el-col :span="5">可选参数值</el-col>
              </el-row>
              <el-row :gutter="20" v-for="(item, index) in editForm.params" :key="'params' + index">
                <el-col :span="5">
                  <el-form-item
                    :prop="'params.' + index + '.paramNm'"
                    :rules="[
                      {
                        required: true,
                        message: '参数名称不能为空',
                        trigger: 'blur'
                      },
                      { max: 100, message: '参数名称不能超过100个字符', trigger: 'blur' }
                    ]"
                  >
                    <el-input v-model="item.paramNm" placeholder="参数名称" :disabled="!editable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item
                    :prop="'params.' + index + '.paramType'"
                    :rules="{
                      required: true,
                      message: '参数类型不能为空',
                      trigger: 'change'
                    }"
                    label-width="0"
                  >
                    <el-select v-model="item.paramType" :disabled="!editable">
                      <el-option label="---" value=""></el-option>
                      <el-option
                        v-for="item in $dictList('value_type')"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="2" align="center">
                  <el-form-item :prop="'params.' + index + '.enumTag'" label-width="0">
                    <el-checkbox v-model="item.enumTag" :true-label="1" :false-label="0"></el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item
                    :prop="'params.' + index + '.fieldNm'"
                    :rules="{
                      required: true,
                      message: '参数字段不能为空',
                      trigger: 'blur'
                    }"
                    label-width="0"
                  >
                    <el-input v-model="item.fieldNm" placeholder="参数字段" :disabled="!editable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5" :align="item.enumTag === 1 ? 'none' : 'center'">
                  <el-form-item
                    :prop="'params.' + index + '.optParamVal'"
                    :rules="item.enumTag === 1 ? { required: true, message: '参数值不能为空', trigger: 'change' } : {}"
                  >
                    <el-input
                      v-model="item.optParamVal"
                      placeholder="可选参数值"
                      readonly
                      class="enums-box"
                      v-if="item.enumTag === 1"
                      @click.native="$refs.enumsDialog.showDialog({ optParamVal: item.optParamVal, index: index })"
                    ></el-input>
                    <span v-else>---</span>
                  </el-form-item>
                </el-col>
                <el-col :span="4" v-if="editable">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    circle
                    @click="addParams('params')"
                  ></el-button>
                  <el-button
                    type="warning"
                    icon="el-icon-minus"
                    size="mini"
                    circle
                    @click="remove('params', index)"
                    v-if="index !== 0"
                  ></el-button>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-form>
      </template>
      <template v-else>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-purpose">数据源</div>
              <div class="source-content">{{ tagInfo.plfm }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-purpose">数据库</div>
              <div class="source-content">{{ tagInfo.db }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-blue">数据表</div>
              <div class="source-content">{{ tagInfo.table }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-blue">{{ tagInfo.tagKind === 4 ? '事件ID' : '字段' }}</div>
              <div class="source-content">{{ tagInfo.field }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-cyan">关联字段</div>
              <div class="source-content">{{ tagInfo.relaFields.join(',') }}</div>
            </div>
          </el-col>
          <el-col :span="12" v-if="tagInfo.tagKind !== 4">
            <div class="source-item">
              <div class="source-title linear-cyan">取值类型</div>
              <div class="source-content">{{ tagInfo.valueType }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-red">更新频率</div>
              <div class="source-content">{{ tagInfo.updateFreq }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-red">更新规则<freq-tips></freq-tips></div>
              <div class="source-content">
                {{ tagInfo.updateFreqId === 3 && tagInfo.updateFreqValue == '0' ? '月末' : tagInfo.updateFreqValue }}
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-item">
              <div class="source-title linear-purpose">标签编码</div>
              <div class="source-content">{{ tagInfo.tagCode }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="tagInfo.syncRecords.length">
          <el-col :span="24">
            <div class="source-item sync-item">
              <div class="source-title linear-blue"><span>数据同步</span></div>
              <div class="source-content">
                <el-row class="sync-row-title">
                  <el-col :span="6">同步平台</el-col>
                  <el-col :span="6">同步数据库</el-col>
                  <el-col :span="6">同步数据表</el-col>
                  <el-col :span="6">同步字段</el-col>
                </el-row>
                <el-row v-for="item in tagInfo.syncRecords" :key="item.plfmId">
                  <el-col :span="6" align="center">{{ item.syncPlfmNm }}</el-col>
                  <el-col :span="6" align="center">{{ item.syncDbNm }}</el-col>
                  <el-col :span="6" align="center">{{ item.syncTableNm }}</el-col>
                  <el-col :span="6" align="center"> {{ item.syncFieldNm }}</el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="source-params left">
              <div class="params-title">
                <icon-svg name="iconTech"></icon-svg><br />
                是否枚举值<br />({{ tagInfo.enumTag === 1 ? '是' : '否' }})
              </div>
              <div class="params-content">
                <!-- <tag-params-table :dataList="tagInfo.enumVals" type="enum"></tag-params-table> -->
                <div class="content-top clearfix">
                  <el-col :span="9" align="center"><span>枚举值</span></el-col>
                  <el-col :span="15" align="center"><span>描述</span></el-col>
                </div>
                <!-- <ul class="tag-scrollbar">
                  <li v-for="(item, index) in tagInfo.enumVals" :key="index" class="clearfix">
                    <el-row>
                      <el-col :span="9" align="center">{{ item.cdVal }}</el-col>
                      <el-col :span="15" align="center">{{ item.cdDesc }}</el-col>
                    </el-row>
                  </li>
                </ul> -->
                <tag-enums :tagId="tagId"></tag-enums>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="source-params right">
              <div class="params-title">
                <icon-svg name="iconBase"></icon-svg><br />
                是否带参数<br />({{ tagInfo.haveParam === 1 ? '是' : '否' }})
              </div>
              <div class="params-content">
                <!-- <tag-params-table :dataList="tagInfo.enumVals" type="enum"></tag-params-table> -->
                <div class="content-top clearfix">
                  <el-row :gutter="5">
                    <el-col :span="6" align="center"><span>名称</span></el-col>
                    <el-col :span="5" align="center"><span>类型</span></el-col>
                    <el-col :span="6" align="center"><span>字段</span></el-col>
                    <el-col :span="7" align="center"><span>参数值</span></el-col>
                  </el-row>
                </div>
                <ul class="tag-scrollbar">
                  <li v-for="(item, index2) in tagInfo.params" :key="index2" class="clearfix">
                    <el-row :gutter="5">
                      <el-col :span="6" align="center">{{ item.paramNm }}</el-col>
                      <el-col :span="5" align="center">{{ $dict('value_type')[item.paramType] }}</el-col>
                      <el-col :span="6" align="center">{{ item.fieldNm }}</el-col>
                      <el-col :span="7" align="center">{{ item.optParamVal }}</el-col>
                    </el-row>
                  </li>
                </ul>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </div>
    <div class="content-handler" v-if="tagStatus === 50 && !isModify">
      <el-button type="primary" v-if="!editable" @click="editable = true">编辑</el-button>
      <el-button v-if="editable" @click="cancelEdit">取消</el-button>
      <el-button type="primary" v-if="editable" @click="submit">保存</el-button>
    </div>
    <enums-dialog ref="enumsDialog" @updateParams="updateParams"></enums-dialog>
    <register-manual-drawer ref="registerManualDrawer" @callback="setManualData"></register-manual-drawer>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import enumsDialog from '@/components/tag-enums-dialog'
import registerManualDrawer from '../register/batch/register-manual-batch'
import freqTips from '@/components/tag-freq-tips'
export default {
  components: {
    enumsDialog,
    registerManualDrawer,
    freqTips
  },
  props: {
    tagId: {
      type: String,
      required: true,
      default: ''
    },
    tagStatus: {
      type: Number,
      default: 50
    },
    isModify: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      firstLoad: true,
      editable: false,
      platforms: [],
      dbList: [],
      tableList: [],
      editForm: {
        plfmId: '',
        dbNm: '',
        tableNm: '',
        fieldNm: '',
        relaFields: [],
        valueTypeId: '',
        updateFreqValue: '',
        updateFreqId: '',
        syncRecords: [],
        enumTag: '',
        enumVals: [{ cdVal: '', cdDesc: '' }],
        haveParam: '',
        params: [{ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' }],
        isEnumImport: false
      },
      editFormRules: {
        plfmId: [{ required: true, message: '平台不能为空', trigger: 'change' }],
        dbNm: [{ required: true, message: '数据库不能为空', trigger: 'change' }],
        tableNm: [{ required: true, message: '数据表不能为空', trigger: 'change' }],
        fieldNm: [{ required: true, message: '字段不能为空', trigger: 'blur' }],
        valueTypeId: [{ required: true, message: '取值类型不能为空', trigger: 'change' }],
        updateFreqId: [{ validator: this.$checkBoolNum('更新频率必须选择'), trigger: 'change' }],
        enumTag: [{ validator: this.$checkBoolNum('是否枚举必须选择'), trigger: 'change' }],
        haveParam: [{ validator: this.$checkBoolNum('是否带参数必须选择'), trigger: 'change' }]
      },
      numberRules: (rule, value, callback) => {
        if (value === '') callback()
        else {
          if (isNaN(value)) callback(new Error('只能输入大于0的正整数'))
          else {
            if (Number(value) > 0) {
              if (Number(value) % 1 === 0) callback()
              else callback(new Error('只能输入大于0的正整数'))
            } else callback(new Error('只能输入大于0的正整数'))
          }
        }
      },
      formInfo: {},
      tagInfo: {
        plfm: '',
        db: '',
        table: '',
        tagKind: '',
        field: '',
        relaFields: [],
        valueType: '',
        updateFreq: '',
        updateFreqId: '',
        updateFreqValue: '',
        tagCode: '',
        syncRecords: [],
        enumTag: '',
        enumVals: [],
        haveParam: '',
        params: []
      },
      checkSyncForm: (rule, value, callback) => {
        let field = rule.field.split('.')[0]
        let fieldname = field.split('[')[0]
        let index = Number(field.split('[')[1].split(']')[0])
        if (this.editForm[fieldname][index].checked) {
          if (!value) callback(new Error('数据同步项不能为空'))
          else {
            let patt = /^[0-9a-zA-Z_]{1,}$/
            if (!patt.test(value)) {
              callback(new Error('数据同步项只能输入字母数字和下划线'))
            } else {
              const avalue = [...new Set(value.trim().split(''))]
              if (!isNaN(value)) {
                callback(new Error('数据同步项不能为纯数字'))
              } else if (!isNaN(value.substr(0, 1))) {
                callback(new Error('数据同步项首字母不能为数字'))
              } else if (avalue.length == 1 && avalue[0] === '_') {
                callback(new Error('数据同步项不能为纯下划线'))
              } else callback()
            }
          }
        } else callback()
      },
      pickOptions: {
        disabledDate(time) {
          return time.getTime() > new Date().getTime()
        }
      },
      MonthPickOptions: {
        disabledDate(time) {
          const year = new Date().getFullYear()
          const beginTime = new Date(year - 1 + '-12-31 23:59:59')
          const endTime = new Date(year + '-12-31 23:59:59')
          return !(time.getTime() > beginTime.getTime() && time.getTime() < endTime.getTime())
        }
      }
    }
  },
  created() {
    this.getPlatforms()
  },
  watch: {
    tagId() {
      this.editable = false
      this.getPlatforms()
    },
    'editForm.plfmId'(val) {
      this.dbList = []
      this.tableList = []
      this.editForm.dbNm = ''
      this.editForm.tableNm = ''
      this.editForm.relaFields = []
      this.initSyncRecords()
      if (val) this.getDbList()
    },
    'editForm.dbNm'(val) {
      this.tableList = []
      this.editForm.tableNm = ''
      this.editForm.relaFields = []
      if (val) this.getTableList()
    },
    'editForm.tableNm'(val) {
      this.editForm.relaFields = []
      if (val && !this.firstLoad) this.getRelaFields()
    }
  },
  methods: {
    removeTable() {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astData/import/deleteBatchRecords/${this.tagId}`),
        method: 'delete',
        params: this.$ajax.setParams()
      }).then(() => {
        this.editForm.plfmId = ''
        this.editForm.dbNm = ''
        this.editForm.tableNm = ''
      })
    },
    initSyncRecords() {
      let index = this.editForm.syncRecords.findIndex(item => item.syncPlfmId === this.editForm.plfmId)
      if (index >= 0) this.editForm.syncRecords.splice(index, 1)
      this.platforms.forEach(platform => {
        if (
          platform.plfmId !== this.editForm.plfmId &&
          !this.editForm.syncRecords.find(item => item.syncPlfmId === platform.plfmId)
        ) {
          this.editForm.syncRecords.push({
            checked: false,
            syncPlfmId: platform.plfmId,
            syncPlfmNm: platform.plfmNm,
            syncDbNm: '',
            syncTableNm: '',
            syncFieldNm: ''
          })
        }
      })
    },
    changeSync(val, index) {
      if (!val) {
        this.editForm.syncRecords[index].syncDbNm = ''
        this.editForm.syncRecords[index].syncTableNm = ''
        this.editForm.syncRecords[index].syncFieldNm = ''
      }
    },
    clearUpdateValue() {
      this.editForm.updateFreqValue = ''
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTag/getDataRela/${this.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.plfmId = data.data.plfmId
          this.editForm.valueTypeId = data.data.valueTypeId
          this.editForm.updateFreqId = data.data.updateFreqId
          this.editForm.updateFreqValue = data.data.updateFreqValue
            ? data.data.updateFreqId === 4
              ? new Date().getFullYear() + '-' + data.data.updateFreqValue
              : data.data.updateFreqValue
            : ''
          this.editForm.enumTag = data.data.enumTag
          this.editForm.enumVals = data.data.enumVals.length ? data.data.enumVals : [{ cdVal: '', cdDesc: '' }]
          if ((data.data.enumTag === 1 && !data.data.enumVals.length) || data.data.enumVals.length > 10)
            this.editForm.isEnumImport = true
          this.editForm.haveParam = data.data.haveParam
          this.editForm.params = data.data.params.length
            ? data.data.params
            : [{ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' }]
          this.editForm.fieldNm = data.data.field
          this.$nextTick(() => {
            this.editForm.dbNm = data.data.db
            this.$nextTick(() => {
              this.editForm.tableNm = data.data.table
              this.$nextTick(() => {
                this.editForm.relaFields = data.data.relaFields
                this.firstLoad = false
                this.$nextTick(() => (this.formInfo = cloneDeep(this.editForm)))
              })
            })
          })
          this.$nextTick(() => {
            // 同步数据
            data.data.syncRecords.forEach(item => {
              let index = this.editForm.syncRecords.findIndex(value => value.syncPlfmId === item.syncPlfmId)
              if (index >= 0) {
                this.editForm.syncRecords[index].checked = true
                this.editForm.syncRecords[index].syncDbNm = item.syncDbNm
                this.editForm.syncRecords[index].syncFieldNm = item.syncFieldNm
                this.editForm.syncRecords[index].syncTableNm = item.syncTableNm
              }
            })
          })
          this.tagInfo = {
            plfm: data.data.plfm,
            db: data.data.db,
            table: data.data.table,
            tagKind: data.data.tagKind,
            field: data.data.field,
            relaFields: data.data.relaFields,
            valueType: data.data.valueType,
            updateFreq: data.data.updateFreq,
            updateFreqId: data.data.updateFreqId,
            updateFreqValue: data.data.updateFreqValue,
            tagCode: data.data.tagCode,
            syncRecords: data.data.syncRecords,
            enumTag: data.data.enumTag,
            enumVals: data.data.enumVals,
            haveParam: data.data.haveParam,
            params: data.data.params
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getPlatforms() {
      this.$ajax({
        url: this.$ajax.setUrl('mta/mtaPlatform/getAll'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.platforms = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getDbList() {
      this.$ajax({
        url: this.$ajax.setUrl(`mta/mtaDatabase/plfmId/${this.editForm.plfmId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dbList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getTableList() {
      this.$ajax({
        url: this.$ajax.setUrl(`mta/mtaTable/getTableList/${this.editForm.plfmId}/${this.editForm.dbNm}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tableList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getRelaFields() {
      this.$ajax({
        url: this.$ajax.setUrl(
          `mta/mtaField/getRelaFieldList/${this.editForm.plfmId}/${this.editForm.dbNm}/${this.editForm.tableNm}`
        ),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.relaFields = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    addParams(name) {
      if (name === 'enumVals') this.editForm[name].push({ cdVal: '', cdDesc: '' })
      else this.editForm[name].push({ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' })
    },
    remove(name, index) {
      this.editForm[name].splice(index, 1)
    },
    updateParams(opt, index) {
      this.editForm.params[index].optParamVal = opt
    },
    submit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          this.editForm.params.forEach(v => {
            v.plfmId = this.editForm.plfmId
            v.dbName = this.editForm.dbNm
            v.tableNm = this.editForm.tableNm
            v.tagId = this.tagId
          })
          let syncRecords = []
          this.editForm.syncRecords.forEach(item => {
            if (item.checked)
              syncRecords.push({
                syncDbNm: item.syncDbNm,
                syncFieldNm: item.syncFieldNm,
                syncPlfmId: item.syncPlfmId,
                syncPlfmNm: item.syncPlfmNm,
                syncTableNm: item.syncTableNm,
                tagId: this.tagId
              })
          })
          this.editForm.params.forEach(item => {
            if (!item.enumTag) item.optParamVal = ''
          })
          if (this.editForm.enumVals.length && !this.editForm.enumVals[0].cdVal) this.editForm.enumVals.splice(0, 1)
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('ast/astTag/updateDataRela'),
            method: 'post',
            data: this.$ajax.setData({
              db: this.editForm.dbNm,
              enumTag: this.editForm.enumTag,
              enumVals: this.editForm.enumVals,
              field: this.editForm.fieldNm,
              relaFields: this.editForm.relaFields,
              haveParam: this.editForm.haveParam,
              params: this.editForm.params,
              plfmId: this.editForm.plfmId,
              tagId: this.tagId,
              table: this.editForm.tableNm,
              updateFreqId: this.editForm.updateFreqId,
              updateFreqValue: this.editForm.updateFreqValue
                ? this.editForm.updateFreqId === 4
                  ? this.editForm.updateFreqValue.substring(5)
                  : this.editForm.updateFreqValue
                : '',
              valueTypeId: this.tagInfo.tagKind === 4 || this.tagInfo.tagKind === 5 ? 1 : this.editForm.valueTypeId,
              syncRecords: syncRecords
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              this.editable = false
              this.getDetail()
              this.$emit('callback')
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    cancelEdit() {
      this.reset()
      this.editable = false
    },
    clearForm() {
      this.scenes = []
      this.platforms = []
      this.editForm = {
        plfmId: '',
        dbNm: '',
        tableNm: '',
        fieldNm: '',
        relaFields: [],
        valueTypeId: '',
        updateFreqId: '',
        updateFreqValue: '',
        syncRecords: [],
        enumTag: '',
        enumVals: [{ cdVal: '', cdDesc: '' }],
        isEnumImport: false,
        haveParam: '',
        params: [{ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' }]
      }
      this.tagInfo = {
        plfm: '',
        db: '',
        table: '',
        tagKind: '',
        field: '',
        relaFields: [],
        valueType: '',
        updateFreq: '',
        updateFreqId: '',
        updateFreqValue: '',
        syncRecords: [],
        enumTag: '',
        enumVals: [],
        haveParam: '',
        params: []
      }
      if (this.editable)
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
          this.editable = false
          this.firstLoad = true
        })
    },
    setManualData(data) {
      if (data) {
        this.editForm.plfmId = data.plfmId
        this.$nextTick(() => {
          this.editForm.dbNm = data.dbNm
          this.$nextTick(() => (this.editForm.tableNm = data.tableNm))
        })
      }
    },
    reset() {
      let info = cloneDeep(this.formInfo)
      this.editForm.plfmId = info.plfmId
      this.editForm.fieldNm = info.fieldNm
      this.editForm.valueTypeId = info.valueTypeId
      this.editForm.updateFreqId = info.updateFreqId
      this.editForm.updateFreqValue = info.updateFreqValue
      this.editForm.enumTag = info.enumTag
      this.editForm.enumVals = info.enumVals
      this.editForm.isEnumImport = info.isEnumImport
      this.editForm.haveParam = info.haveParam
      this.editForm.params = info.params
      this.$nextTick(() => {
        this.editForm.dbNm = info.dbNm
        this.$nextTick(() => {
          this.editForm.tableNm = info.tableNm
          this.$nextTick(() => {
            this.editForm.relaFields = info.relaFields
            this.$nextTick(() => {
              this.editForm.syncRecords = info.syncRecords
            })
          })
        })
      })
    }
  }
}
</script>

<style lang="scss">
.info-source {
  .el-input.is-disabled .el-input__inner {
    color: #303133;
  }
  .content-form > :last-child {
    margin-bottom: 10px;
  }
  .params-selection {
    width: 500px;
    margin-top: 10px;
    box-shadow: #eee 0 0 10px;
    position: relative;
  }
  .params {
    padding: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    &:before {
      width: 5px;
      content: '';
      background: linear-gradient(#6464c8, #7173e0);
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
    }
    & > .el-form-item:first-child {
      margin-left: -20px;
    }
    .params-title {
      font-weight: bold;
      text-align: center;
      margin-bottom: 5px;
    }
    li {
      margin-bottom: 10px;
      & + li {
        padding: 10px 0;
      }
    }
  }
  .source-item {
    width: 100%;
    height: 45px;
    margin-bottom: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    &.sync-item {
      font-size: 14px;
      height: auto;
      .source-title {
        font-size: 16px;
        height: 100%;
        span {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .el-input {
        padding: 0 5px !important;
      }
      .el-input__inner {
        height: 35px !important;
        line-height: 35px !important;
        border: 1px solid #dcdfe6 !important;
      }
      .sync-row-title {
        font-size: 16px;
        font-weight: bold;
        text-align: center;
      }
      .el-col {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .source-title {
      font-weight: bold;
      width: 150px;
      padding-left: 50px;
      line-height: 45px;
      color: #fff;
      position: absolute;
      &:before {
        width: 10px;
        height: 10px;
        content: '';
        background-color: #eee9ff;
        border: 2px solid #cfc7ee;
        margin-top: -5px;
        position: absolute;
        top: 50%;
        left: 20px;
        border-radius: 50%;
      }
      &:after {
        width: 0;
        height: 0;
        content: '';
        margin-top: -10px;
        border-top: 10px solid transparent;
        border-bottom: 10px solid transparent;
        position: absolute;
        top: 50%;
        right: -10px;
      }
      &.linear-purpose:after {
        border-left: 10px solid #7c6bed;
      }
      &.linear-blue:after {
        border-left: 10px solid #635fd7;
      }
      &.linear-cyan:after {
        border-left: 10px solid #0696ec;
      }
      &.linear-red:after {
        border-left: 10px solid #c563ee;
      }
    }
    .source-content {
      line-height: 45px;
      padding: 0 30px 0 180px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &.rela-content {
        padding-left: 195px;
      }
    }
    .el-select .el-input__inner,
    .el-input .el-input__inner {
      height: 45px;
      line-height: 45px;
      border: 0;
    }
  }
  .source-params {
    width: 100%;
    min-height: 40px;
    margin-bottom: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    .params-title {
      font-weight: bold;
      width: 150px;
      padding: 20px 0 30px 0;
      text-align: center;
      color: #fff;
      line-height: 40px;
      background-size: 100% 100%;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      svg {
        width: 45px;
        height: 45px;
        opacity: 0.4;
      }
    }
    .params-content {
      font-size: 15px;
      padding-left: 150px;
      .content-top {
        padding: 5px 0;
        border-bottom: 1px solid $border-color;
        span {
          display: inline-block;
          width: 100%;
          padding: 5px 10px;
          background-color: #fcf5e5;
          border-radius: 15px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      ul {
        height: 200px;
        background-color: #fff;
        overflow-x: hidden;
        overflow-y: auto;
        li {
          line-height: 40px;
          .el-col {
            min-height: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
      .tag-enums {
        ul {
          height: auto;
        }
        & > ul {
          height: 168px;
        }
      }
    }
    &.left {
      .params-title {
        background: #616bc4 url(~@/assets/img/params_bg.png) no-repeat;
        background-size: cover;
      }
      .dot {
        background-color: #ff9d2e;
      }
    }
    &.right {
      .params-title {
        background: #a58ff1 url(~@/assets/img/params_bg.png) no-repeat;
        background-size: cover;
      }
      .dot {
        background-color: #74c7bd;
      }
    }
  }
  .el-input-number {
    .el-input__inner {
      padding: 0 15px;
      text-align: left;
    }
    .el-input-number__decrease,
    .el-input-number__increase {
      display: none;
    }
  }
  .manual-tips {
    margin-left: 10px;
    color: $tag-green;
    & + .deleteBtn {
      float: right;
    }
  }
}
</style>
